import * as app from '../../common/utils/BaseApp'
import { deepClone } from '@/utils'
import * as utils from '@/utils/verify'
import { flatArrayToTree } from '../../common/utils/ComUtil'
import store from '@/store'

import { getAllNormalRoleList } from '@/api/system/role'
import { getPrivilegeByRole, updatePrivilege } from '@/api/system/privilege'
import { getMenuAllList } from '@/api/system/menu'
import langFile from './perm.lang'
const base = app.install({ langObj: langFile })
// const pageMode = {
//   add: 'add',
//   detailAdd: 'detailAdd',
//   update: 'update'
// }
export default {
  mixins: [base],
  data() {
    return {
      formObj: {
        checkAllFlg: { }, // 全选CheckBox
        isIndeterminate: { }, // 半选标志
        checkedItems: { }, // 选中功能列表
        bakCheckedItems: { }, // 临时保存
        moduleAllList: [], // 模块列表
        menuAllObj: {}, // 菜单列表
        moduleAllObj: [], // 模块对象
        roleTreeData: {
          data: [],
          selectedNode: null
        }
      }
    }
  },
  async created() {
    this.$gcom.formObj = deepClone(this.formObj)
    await this.searchAllRoleList()
    await this.searchMenuList()
    await this.searchRolePermList()
  },
  methods: {
    getLangField() {
      let menuNameField = 'displayNameZh'
      if (store.getters.language === 'ja') {
        menuNameField = 'displayNameJa'
      } else if (store.getters.language === 'en') {
        menuNameField = 'displayNameEn'
      }
      return menuNameField
    },
    async searchAllRoleList() {
      const result = await getAllNormalRoleList()
      const roleList = result.data.listLine.map((item) => {
        return { id: item.roleId, name: item.roleName, parentId: '' }
      })
      const _target = this.formObj.roleTreeData
      _target.data = flatArrayToTree(roleList, { exclude: [] })
      if (_target.data.length > 0) {
        // 默认选中节点第一个，node-key： 每个树节点用来作为唯一标识的属性
        _target.selectedNode = _target.data[0]
      }
    },
    async searchMenuList() {
      try {
        const result = await getMenuAllList({
          searchForm: {},
          likeSearch: []
        })
        const listLine = result.data.listLine.map((item) => {
          if (item.menuType === '1' || item.menuType === '2') { // 模块,菜单
            this.$set(this.formObj.checkAllFlg, item.menuId, false)
            this.$set(this.formObj.isIndeterminate, item.menuId, false)
          }
          if (item.menuType === '2') { // 菜单
            this.$set(this.formObj.checkedItems, item.menuId, [])
          }
          const langVal = utils.isNotContainsVal(item[this.getLangField()]) ? item.displayNameZh : item[this.getLangField()]
          item.menuName = langVal
          return item
        })

        // 临时保存
        this.formObj.bakCheckedItems = deepClone(this.formObj.checkedItems)

        this.formObj.moduleAllObj = {}
        this.formObj.menuAllObj = {}
        this.formObj.moduleAllList = flatArrayToTree(listLine, { schema: { id: 'menuId', name: 'routeName', parentId: 'menuParent' }})
        this.formObj.moduleAllList.forEach((mudule) => {
          this.formObj.moduleAllObj[mudule.menuId] = mudule
          mudule.children.forEach((menu) => {
            this.formObj.menuAllObj[menu.menuId] = menu
          })
        })
      } catch (err) {
        console.log(err)
      } finally {
        // setTimeout(() => {
        //   _target.listLineLoading = false
        // }, 0)
      }
    },
    async searchRolePermList() {
      const _target = this.formObj.roleTreeData

      const result = await getPrivilegeByRole({
        searchForm: { roleId: _target.selectedNode.id },
        likeSearch: []
      })
      const _rst = this.formObj.checkedItems
      result.data.listLine.forEach((item) => {
        if (_rst[item.menuParent] !== undefined) {
          _rst[item.menuParent].push(item.menuId)
        }
      })
      Object.keys(_rst).forEach((menuId) => {
        this.handleCheckedPerm(menuId)
      })
    },
    // 角色节点单击事件
    async handleTreeNodeClick(node) {
      const _target = this.formObj.roleTreeData
      _target.selectedNode = node
      // 根据选中组织查询所属用户
      this.formObj.checkedItems = deepClone(this.formObj.bakCheckedItems)
      await this.searchRolePermList()
    },
    async handleSavePerm() {
      const updData = {
        perm: this.formObj.checkedItems,
        roleId: this.formObj.roleTreeData.selectedNode.id
      }
      await updatePrivilege(updData)
      await this.searchMenuList()
      await this.searchRolePermList()
    },
    // ----------------------- 模块全选/全取消处理 ---------------------
    setModuleCheckAllFlg(_moduleData, _moduleId) {
      // 判断是否模块下面的所有 菜单全部设定了权限
      const realMenu = _moduleData.children.map((menu) => {
        return { menuId: menu.menuId, checkedLen: this.formObj.checkedItems[menu.menuId].length, childLen: menu.children.length }
      }).filter((menu) => {
        return menu.childLen > 0
      })
      const allChecked = realMenu.filter((menu) => {
        return menu.checkedLen === menu.childLen
      })
      const allUnchecked = realMenu.filter((menu) => {
        return menu.checkedLen === 0
      })
      const partChecked = realMenu.filter((menu) => {
        return menu.checkedLen > 0
      })

      if (realMenu.length === 0) { // 没有选项
        this.formObj.isIndeterminate[_moduleId] = false
        this.formObj.checkAllFlg[_moduleId] = false
      } else if (realMenu.length === allChecked.length) { // 全部选中
        // 模块全选：全选中
        this.formObj.isIndeterminate[_moduleId] = false
        this.formObj.checkAllFlg[_moduleId] = true
      } else if (realMenu.length === allUnchecked.length) { // 全部未选中
        // 模块全选：取消全选中
        this.formObj.isIndeterminate[_moduleId] = false
        this.formObj.checkAllFlg[_moduleId] = false
      } else if (partChecked.length > 0) { // 部分选中
        // 模块全选：取消全选中
        this.formObj.isIndeterminate[_moduleId] = true
        this.formObj.checkAllFlg[_moduleId] = false
      }
    },
    // ----------------------- 功能权限选择处理 ---------------------
    handleCheckedPerm(menuId) {
      const _menuData = this.formObj.menuAllObj[menuId]
      const _moduleData = this.formObj.moduleAllObj[_menuData.menuParent]
      const _moduleId = _moduleData.menuId
      const _checkedItems = this.formObj.checkedItems[menuId]
      const isAllChecked = _checkedItems.length === _menuData.children.length
      if (isAllChecked) {
        // 菜单全选：全选中
        this.formObj.isIndeterminate[menuId] = false
        this.formObj.checkAllFlg[menuId] = true

        // 判断是否模块下面的所有 菜单全部设定了权限
        this.setModuleCheckAllFlg(_moduleData, _moduleId)
      } else {
        // 菜单全选：取消全选中
        this.formObj.checkAllFlg[menuId] = false
        // 模块全选：取消全选中
        this.formObj.checkAllFlg[_moduleId] = false

        // 部分选中
        if (_checkedItems.length > 0) {
          // 菜单全选：取消全选中
          this.formObj.isIndeterminate[menuId] = true
          // 模块全选：取消全选中
          this.formObj.isIndeterminate[_moduleId] = true
        } else { // 全部未选中
          // 菜单全选：取消全选中
          this.formObj.isIndeterminate[menuId] = false
          // 判断是否模块下面的所有 菜单全部设定了权限
          this.setModuleCheckAllFlg(_moduleData, _moduleId)
        }
      }
    },
    // ----------------------- 菜单Checkbox选择处理 ---------------------
    handleCheckMenuAll(menuId, checked) {
      const _menuData = this.formObj.menuAllObj[menuId]
      const _moduleData = this.formObj.moduleAllObj[ _menuData.menuParent]
      const _moduleId = _moduleData.menuId
      if (checked) { // 全选
        // 功能全选：全选中
        this.formObj.checkedItems[menuId] = _menuData.children.map((item) => {
          return item.menuId
        })

        this.formObj.isIndeterminate[menuId] = false
        this.formObj.checkAllFlg[menuId] = true
      } else {
        // 功能全选：取消全选中
        this.formObj.checkedItems[menuId] = []
        this.formObj.isIndeterminate[menuId] = false
        this.formObj.checkAllFlg[menuId] = false
      }

      // 判断是否模块下面的所有 菜单全部设定了权限
      this.setModuleCheckAllFlg(_moduleData, _moduleId)
    },
    // ----------------------- 模块Checkbox选择处理 ---------------------
    handleCheckModuleAll(moduleId, checked) {
      const _moduleData = this.formObj.moduleAllObj[moduleId]
      _moduleData.children.forEach((menu) => {
        if (menu.children.length > 0) {
          this.handleCheckMenuAll(menu.menuId, checked)
        }
      })
    },
    // ----------------------- Open Dialog ---------------------
    openDialog(target, mode, row, index) {
      const data = row === undefined ? this.$gcom.formObj.addForm[target] : row
      this.formObj.addForm[target] = { ...data }
      this.formObj.addForm.showFlg[target] = true
      this.formObj.addForm.showMode[target] = mode
    }
  }
}
